#!/usr/bin/env python
#coding=utf-8

import socket,select,Queue

server = socket.socket()
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 10001))
server.listen(1)

inputs, outputs = [], []
inputs.append(server)

message_queue = {}

while inputs:
	print [i.fileno() for i in ]
	list_read, list_write, list_exec = select.select(inputs, outputs, inputs)
	for r in list_read:
		if r is server:
			conn, clie_addr = r.accept()
			print 'connected from ', clie_addr
			inputs.append(conn)
			message_queue[conn] = Queue.Queue()
		else:
			data = r.recv(1024)
			if not data:
				print 'close', r.getpeername()
				inputs.remove(r)
				if r in outputs:
					outputs.remove(r)
				r.close()
			else:
				cmd, msg = data.split('\t')[:2]
				print 'recv', data, r.getpeername()
				if cmd == 'show':
					#get all name ,return to client
					pass
				elif cmd == 'name':
					#notified all who is comming
					name_connect[r] = msg
					for r in name_connect:
						message_queue[r].put('%s is comming, welcome' % msg)

	for r in list_write:
		data = message_queue.get_nowait()
		if data:
			r.sendall(data)

	for i in list_exec:
		inputs.remove(r)
		if r in outputs:
			outputs.remove(r)
		r.close()